package com.dingyx.ps.repository;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dingyx.ps.mapper.TaskMasterMapper;
import com.dingyx.ps.mapper.TaskSlaverMapper;
import com.dingyx.ps.model.export.TaskMasterExport;
import com.dingyx.ps.model.export.TaskMasterLtcExport;
import com.dingyx.ps.model.entity.TaskMasterDTO;
import com.dingyx.ps.model.entity.TaskSlaverDTO;
import com.dingyx.ps.model.po.TaskSlaverPO;
import com.dingyx.ps.model.po.TaskMasterPO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author dingyuxin
 *
 */
@Repository
public class TaskRepository {
    @Resource
    private TaskMasterMapper taskMasterMapper;
    @Resource
    private TaskSlaverMapper taskSlaverMapper;


    /**
     * 根据任务id查询主任务详情
     *
     * @param taskId
     * @return
     */
    public TaskMasterDTO selectTaskMasterByTaskId(Long taskId) {
        return taskMasterMapper.selectById(taskId);
    }

    /**
     * 根据子任务id查询子任务详情
     *
     * @param unitTaskId
     * @return
     */
    public TaskSlaverDTO selectByUnitTaskId(Long unitTaskId) {
        return taskSlaverMapper.selectById(unitTaskId);
    }

    /**
     * 分页查询主任务列表
     *
     * @param param
     * @return
     */
    public IPage<TaskMasterDTO> selectTaskByPage(TaskMasterPO param) {
        Page<TaskMasterDTO> page = new Page<>(param.getPageNum(), param.getPageSize());
        if (param.getSource().equalsIgnoreCase("yonggong")){
            return taskMasterMapper.selectTaskPageList(page, param);
        }else {
            // 非用工自有类型，ltc，pms,ts只有一个明细，需要通过关联sql查询任务明细中的工程师信息
            return taskMasterMapper.selectOtherTaskPageList(page, param);
        }
    }

    /**
     * 导出查询主任务列表
     *
     * @param param
     * @return
     */
    public List<TaskMasterExport> selectTaskToExport(TaskMasterPO param) {
        return taskMasterMapper.selectTaskToExport(param);
    }

    /**
     * 导出查询LTC主任务列表
     *
     * @param param
     * @return
     */
    public List<TaskMasterLtcExport> selectTaskLtcToExport(TaskMasterPO param) {
        QueryWrapper<TaskMasterDTO> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(param.getEnterpriseId())) {
            queryWrapper.eq("enterprise_id", param.getEnterpriseId());
        }
        if (StringUtils.isNotBlank(param.getEnterpriseNameLike())) {
            queryWrapper.like("enterprise_name", param.getEnterpriseNameLike());
        }
        if (StringUtils.isNotBlank(param.getSource())) {
            queryWrapper.eq("source", param.getSource());
        }
        queryWrapper.orderByDesc("create_date");
        List<TaskMasterDTO> taskMasterDTOS = taskMasterMapper.selectList(queryWrapper);
        List<TaskMasterLtcExport> taskMasterLtcExports = new ArrayList<>();
        for (TaskMasterDTO taskMasterDTO : taskMasterDTOS) {
            TaskMasterLtcExport taskMasterLtcExport = new TaskMasterLtcExport();
            BeanUtils.copyProperties(taskMasterDTO, taskMasterLtcExport);
            LocalDateTime publishDate = taskMasterDTO.getPublishDate();
            if (Objects.nonNull(publishDate)) {
                Date publishDates = Date.from(publishDate.atZone(ZoneId.systemDefault()).toInstant());
                taskMasterLtcExport.setPublishDate(publishDates);
            }

            LocalDateTime checkedCompleteDate = taskMasterDTO.getCheckedCompleteDate();
            if (Objects.nonNull(checkedCompleteDate)) {
                Date checkedCompleteDates = Date.from(checkedCompleteDate.atZone(ZoneId.systemDefault()).toInstant());
                taskMasterLtcExport.setCheckedCompleteDate(checkedCompleteDates);
            }
            taskMasterLtcExports.add(taskMasterLtcExport);
        }
        return taskMasterLtcExports;
    }

    /**
     * 分页查询子任务列表
     *
     * @param param
     * @return
     */
    public IPage<TaskSlaverDTO> selectTaskSlaverByPage(TaskSlaverPO param) {
        Page<TaskSlaverDTO> page = new Page<>(param.getPageNum(), param.getPageSize());
        QueryWrapper<TaskSlaverDTO> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(param.getEngineerId())) {
            queryWrapper.eq("engineer_id", param.getEngineerId());
        }
        if (Objects.nonNull(param.getTaskUnitStatus())) {
            queryWrapper.eq("task_unit_status", param.getTaskUnitStatus());
        }
        if (CollectionUtil.isNotEmpty(param.getTaskSlaverStatusList())) {
            queryWrapper.in("task_unit_status", param.getTaskSlaverStatusList());
        }
        if (Objects.nonNull(param.getTaskMasterId())) {
            queryWrapper.eq("task_master_id", param.getTaskMasterId());
        }
        queryWrapper.orderByDesc("create_date");
        return taskSlaverMapper.selectPage(page, queryWrapper);
    }

    /**
     * 根据主任务id查询子任务集合
     *
     * @param masterTaskId
     * @return
     */
    public List<TaskSlaverDTO> selectSlaverListByMasterId(Long masterTaskId) {
        TaskSlaverPO param = new TaskSlaverPO();
        param.setPageNum(1L);
        param.setPageSize(Long.MAX_VALUE);
        param.setTaskMasterId(masterTaskId);
        IPage<TaskSlaverDTO> slaverPage = selectTaskSlaverByPage(param);
        return slaverPage.getRecords();
    }

    public Integer updateTaskEngineer(TaskSlaverDTO taskEngineer) {
        return taskSlaverMapper.updateById(taskEngineer);
    }

    public Integer addTaskMaster(TaskMasterDTO taskMaster) {
        taskMaster.setTaskNo("11LX" + System.currentTimeMillis());
        return taskMasterMapper.insert(taskMaster);
    }

    public Integer addTaskSlaver(TaskSlaverDTO taskSlaver) {
        return taskSlaverMapper.insert(taskSlaver);
    }

    public Integer updateTaskMaster(TaskMasterDTO taskMaster) {
        return taskMasterMapper.updateById(taskMaster);
    }

    public Integer updateTaskSlaver(TaskSlaverDTO updater) {
        return taskSlaverMapper.updateById(updater);
    }

    public Integer deleteSlaverByMasterId(Long masterId) {
        TaskSlaverDTO slaverDTO = new TaskSlaverDTO();
        slaverDTO.setTaskMasterId(masterId);
        return deleteSlaver(slaverDTO);
    }

    public Integer deleteSlaver(TaskSlaverDTO slaverDTO) {
        QueryWrapper<TaskSlaverDTO> wrapper = new QueryWrapper<>();
        if (Objects.nonNull(slaverDTO.getTaskMasterId())) {
            wrapper.eq("task_master_id", slaverDTO.getTaskMasterId());
        }
        return taskSlaverMapper.delete(wrapper);
    }


    /**
     * < 查看上游来源跟上游订单号已有的任务数量 >
     * @author yk
     * @date 2022/3/31 16:17
     * @version v1.0.0
     */
    public Integer selectTaskMasterBySourceNo(String sourceNo,String source){
        return taskMasterMapper.selectCount(new QueryWrapper<TaskMasterDTO>().eq("source_no",sourceNo).eq("source",source));
    }

    /**
     * 根据任务ID集合查询涉及任务明细是否为一个工程师
     *
     * @param taskIds
     * @return
     */
    public List<Integer> selectCountByTaskId(List<Long> taskIds) {
        return taskSlaverMapper.selectCountByTaskId(taskIds);
    }

    /**
     * 根据任务ID集合查询汇总金额
     *
     * @param taskIds
     * @return
     */
    public BigDecimal selectSumMoneyByTaskId(List<Long> taskIds) {
        return taskSlaverMapper.selectSumMoneyByTaskId(taskIds);
    }


    /**
     * 根据结算单查询主任务集合
     *
     * @param accountBillId
     * @return
     */
    public List<TaskMasterDTO> selectTaskMasterByBillId(Long accountBillId) {
        QueryWrapper<TaskMasterDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("account_bill_id", accountBillId);
        return taskMasterMapper.selectList(wrapper);
    }
}